<script setup lang="ts">
import { ref, watch, computed, onMounted, onUnmounted } from 'vue'
import { saveImage, loadImage } from '../services/indexedDBStorage'
import {
  handlePastedImages,
  compressImage,
  generateImageMarkdown,
  extractImageIds,
  createImagePreviewUrl,
  revokeImagePreviewUrl,
  isValidImageFile
} from '../utils/imageUtils'
import { formatFullDateTime } from '../utils/dateUtils'

/**
 * 笔记编辑器组件
 * 支持Markdown编辑、预览和图片粘贴
 */

interface Note {
  id: number
  title: string
  content: string
  folderId: number
  createdAt: string
  updatedAt: string
}

const props = defineProps<{
  note: Note | null
}>()

const emit = defineEmits<{
  updateNote: [note: Partial<Note>]
}>()

// 编辑器状态
const isPreviewMode = ref(false)
const title = ref('')
const content = ref('')

// 保存状态
const saveStatus = ref<'saved' | 'saving' | 'unsaved'>('saved')
const lastSaveTime = ref<string>('')

// 标记是否正在程序化设置内容（避免触发未保存状态）
const isSettingContent = ref(false)

// 监听笔记变化，更新编辑器内容
watch(
  () => props.note,
  (newNote) => {
    isSettingContent.value = true
    if (newNote) {
      title.value = newNote.title
      content.value = newNote.content
      // 重置保存状态
      saveStatus.value = 'saved'
      lastSaveTime.value = ''
    } else {
      title.value = ''
      content.value = ''
      saveStatus.value = 'saved'
      lastSaveTime.value = ''
    }
    // 延迟重置标志，确保watch监听器不会被触发
    setTimeout(() => {
      isSettingContent.value = false
    }, 0)
  },
  { immediate: true }
)

// 监听内容变化，标记为未保存
watch([title, content], () => {
  // 只有在用户编辑时才标记为未保存
  if (props.note && saveStatus.value === 'saved' && !isSettingContent.value) {
    saveStatus.value = 'unsaved'
  }
})

/**
 * 强制保存当前内容
 */
const forceSave = (): void => {
  if (props.note && (saveStatus.value === 'unsaved' || saveStatus.value === 'saving')) {
    // 清除防抖定时器
    if (autoSaveTimer) {
      clearTimeout(autoSaveTimer)
      autoSaveTimer = null
    }
    
    // 立即保存
    saveStatus.value = 'saving'
    emit('updateNote', {
      title: title.value,
      content: content.value,
      updatedAt: formatFullDateTime()
    })
    
    // 更新保存状态
    saveStatus.value = 'saved'
    lastSaveTime.value = new Date().toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  }
}

// 监听笔记切换，强制保存之前的内容
watch(
  () => props.note?.id,
  (newId, oldId) => {
    if (oldId && newId !== oldId) {
      // 笔记切换时强制保存
      forceSave()
    }
  }
)

// 自动保存定时器
let autoSaveTimer: ReturnType<typeof setTimeout> | null = null

// 图片相关状态
const imageCache = ref<Map<string, string>>(new Map())
const isUploading = ref(false)
const uploadProgress = ref(0)

/**
 * 防抖保存函数
 * @param callback 保存回调函数
 */
const debouncedSave = (callback: () => void): void => {
  // 标记为未保存状态
  saveStatus.value = 'unsaved'
  
  if (autoSaveTimer) {
    clearTimeout(autoSaveTimer)
  }
  
  autoSaveTimer = setTimeout(() => {
    saveStatus.value = 'saving'
    callback()
    
    // 保存完成后更新状态
    setTimeout(() => {
      saveStatus.value = 'saved'
      lastSaveTime.value = new Date().toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }, 100)
  }, 500) // 减少到500ms提高响应性
}

/**
 * 处理粘贴事件
 * @param event 粘贴事件
 */
const handlePaste = async (event: ClipboardEvent): Promise<void> => {
  // 防止重复处理
  if (event.defaultPrevented) {
    console.log('粘贴事件已被处理，跳过')
    return
  }

  console.log('=== 粘贴事件开始 ===')
  console.log('事件类型:', event.type)
  console.log('事件目标:', event.target)
  console.log('是否可取消:', event.cancelable)
  console.log('是否已阻止默认行为:', event.defaultPrevented)

  if (!event.clipboardData) {
    console.log('❌ 没有剪贴板数据')
    // 尝试使用navigator.clipboard API作为备用方案
    if (navigator.clipboard && navigator.clipboard.read) {
      console.log('尝试使用navigator.clipboard.read()')
      try {
        const clipboardItems = await navigator.clipboard.read()
        console.log('clipboard.read()结果:', clipboardItems)

        for (const clipboardItem of clipboardItems) {
          console.log('剪贴板项目类型:', clipboardItem.types)

          for (const type of clipboardItem.types) {
            if (type.startsWith('image/')) {
              console.log('发现图片类型:', type)
              const blob = await clipboardItem.getType(type)
              console.log('获取到图片blob:', blob.size, 'bytes')

              // 创建File对象
              const file = new File([blob], `pasted-image.${type.split('/')[1]}`, { type })
              await uploadImages([file])
              event.preventDefault()
              return
            }
          }
        }
      } catch (error) {
        console.log('navigator.clipboard.read()失败:', error)
      }
    }
    return
  }

  console.log('✅ 剪贴板数据可用')
  console.log('剪贴板项目数量:', event.clipboardData.items.length)
  console.log('剪贴板文件数量:', event.clipboardData.files.length)

  // 打印所有剪贴板项目的类型
  for (let i = 0; i < event.clipboardData.items.length; i++) {
    const item = event.clipboardData.items[i]
    console.log(`项目 ${i}: type=${item.type}, kind=${item.kind}`)
  }

  // 打印所有剪贴板文件
  for (let i = 0; i < event.clipboardData.files.length; i++) {
    const file = event.clipboardData.files[i]
    console.log(`文件 ${i}: name=${file.name}, type=${file.type}, size=${file.size}`)
  }

  const images = await handlePastedImages(event.clipboardData)
  console.log('检测到的图片数量:', images.length)

  if (images.length > 0) {
    console.log('🎉 开始处理图片粘贴')
    event.preventDefault()
    await uploadImages(images)
  } else {
    console.log('⚠️ 未检测到图片，允许默认粘贴行为')
  }

  console.log('=== 粘贴事件结束 ===')
}

/**
 * 上传图片
 * @param files 图片文件数组
 */
const uploadImages = async (files: File[]): Promise<void> => {
  if (!props.note) return

  isUploading.value = true
  uploadProgress.value = 0

  try {
    const textarea = document.querySelector('.content-editor') as HTMLTextAreaElement
    const cursorPosition = textarea?.selectionStart || content.value.length

    let insertText = ''

    for (let i = 0; i < files.length; i++) {
      const file = files[i]

      if (!isValidImageFile(file)) {
        console.warn('不支持的图片格式:', file.type)
        continue
      }

      try {
        console.log(`开始处理第 ${i + 1} 张图片:`, file.name, file.type, file.size)

        // 对于小图片，跳过压缩直接使用原文件
        let processedBlob: Blob
        if (file.size < 500 * 1024) {
          // 小于500KB的图片不压缩
          console.log('图片较小，跳过压缩')
          processedBlob = file
        } else {
          console.log('开始压缩图片')
          // 压缩图片
          processedBlob = await compressImage(file, {
            maxWidth: 1920,
            maxHeight: 1080,
            quality: 0.8,
            format: file.type.includes('png') ? 'png' : 'jpeg'
          })
          console.log('图片压缩完成，压缩后大小:', processedBlob.size)
        }

        // 保存到IndexedDB
        console.log('开始保存图片到IndexedDB')
        const imageId = await saveImage({
          name: file.name,
          data: processedBlob,
          type: processedBlob.type,
          size: processedBlob.size
        })
        console.log('图片保存成功，ID:', imageId)

        // 生成Markdown语法
        const markdown = generateImageMarkdown(imageId, file.name)
        insertText += (i > 0 ? '\n' : '') + markdown

        // 创建预览URL并缓存
        const previewUrl = createImagePreviewUrl(processedBlob)
        imageCache.value.set(imageId, previewUrl)
        console.log('预览URL创建成功:', previewUrl)

        uploadProgress.value = ((i + 1) / files.length) * 100
        console.log(`第 ${i + 1} 张图片处理完成`)
      } catch (error) {
        console.error(`第 ${i + 1} 张图片上传失败:`, error)
        console.error('错误详情:', {
          fileName: file.name,
          fileType: file.type,
          fileSize: file.size,
          errorMessage: error instanceof Error ? error.message : String(error),
          errorStack: error instanceof Error ? error.stack : undefined
        })
      }
    }

    if (insertText) {
      // 插入图片Markdown到光标位置
      const newContent =
        content.value.slice(0, cursorPosition) +
        (cursorPosition > 0 ? '\n' : '') +
        insertText +
        (cursorPosition < content.value.length ? '\n' : '') +
        content.value.slice(cursorPosition)

      content.value = newContent
      updateContent()

      // 重新设置光标位置
      setTimeout(() => {
        if (textarea) {
          const newPosition = cursorPosition + insertText.length + (cursorPosition > 0 ? 1 : 0)
          textarea.setSelectionRange(newPosition, newPosition)
          textarea.focus()
        }
      }, 100)
    }
  } catch (error) {
    console.error('批量上传图片失败:', error)
  } finally {
    isUploading.value = false
    uploadProgress.value = 0
  }
}

/**
 * 加载图片预览
 * @param imageId 图片ID
 * @returns Promise<string | null>
 */
const loadImagePreview = async (imageId: string): Promise<string | null> => {
  if (imageCache.value.has(imageId)) {
    return imageCache.value.get(imageId) || null
  }

  try {
    const imageData = await loadImage(imageId)
    if (imageData) {
      const previewUrl = createImagePreviewUrl(imageData.data)
      imageCache.value.set(imageId, previewUrl)
      return previewUrl
    }
  } catch (error) {
    console.error('加载图片失败:', error)
  }

  return null
}

/**
 * 处理拖拽上传
 * @param event 拖拽事件
 */
const handleDrop = async (event: DragEvent): Promise<void> => {
  event.preventDefault()

  if (!event.dataTransfer) return

  const files = Array.from(event.dataTransfer.files).filter((file) => isValidImageFile(file))

  if (files.length > 0) {
    await uploadImages(files)
  }
}

/**
 * 处理拖拽悬停
 * @param event 拖拽事件
 */
const handleDragOver = (event: DragEvent): void => {
  event.preventDefault()
}

/**
 * 清理图片缓存
 */
const cleanupImageCache = (): void => {
  imageCache.value.forEach((url) => {
    revokeImagePreviewUrl(url)
  })
  imageCache.value.clear()
}

// 计算字数
const wordCount = computed(() => {
  return content.value.length
})

/**
 * 更新笔记标题
 */
const updateTitle = (): void => {
  if (props.note) {
    debouncedSave(() => {
      emit('updateNote', {
        title: title.value,
        updatedAt: formatFullDateTime()
      })
    })
  }
}

/**
 * 更新笔记内容
 */
const updateContent = (): void => {
  if (props.note) {
    debouncedSave(() => {
      emit('updateNote', {
        content: content.value,
        updatedAt: formatFullDateTime()
      })
    })
  }
}

/**
 * 切换预览模式
 */
const togglePreview = (): void => {
  isPreviewMode.value = !isPreviewMode.value
}

/**
 * 渲染Markdown内容（支持图片）
 * @param text Markdown文本
 */
const renderMarkdown = (text: string): string => {
  let rendered = text
    // 标题
    .replace(/^### (.*$)/gim, '<h3>$1</h3>')
    .replace(/^## (.*$)/gim, '<h2>$1</h2>')
    .replace(/^# (.*$)/gim, '<h1>$1</h1>')
    // 粗体
    .replace(/\*\*(.*?)\*\*/gim, '<strong>$1</strong>')
    // 斜体
    .replace(/\*(.*?)\*/gim, '<em>$1</em>')
    // 代码块
    .replace(/```([\s\S]*?)```/gim, '<pre><code>$1</code></pre>')
    // 行内代码
    .replace(/`(.*?)`/gim, '<code>$1</code>')
    // 普通链接
    .replace(/\[([^\]]+)\]\((?!image:\/\/)([^)]+)\)/gim, '<a href="$2" target="_blank">$1</a>')

  // 处理图片
  rendered = rendered.replace(/!\[([^\]]*)\]\(image:\/\/([^)]+)\)/gim, (_match, alt, imageId) => {
    const cachedUrl = imageCache.value.get(imageId)
    if (cachedUrl) {
      return `<img src="${cachedUrl}" alt="${alt}" class="markdown-image" />`
    } else {
      // 异步加载图片
      loadImagePreview(imageId).then((url) => {
        if (url) {
          // 触发重新渲染
          setTimeout(() => {
            if (isPreviewMode.value) {
              // 强制更新预览
            }
          }, 100)
        }
      })
      return `<div class="image-loading">加载图片中... (${alt})</div>`
    }
  })

  // 换行
  rendered = rendered.replace(/\n/gim, '<br>')

  return rendered
}

// 全局粘贴事件处理器（备用方案）
let globalPasteHandler: ((event: ClipboardEvent) => void) | null = null

// 组件挂载时加载现有图片
onMounted(async () => {
  console.log('NoteEditor组件已挂载')

  if (props.note?.content) {
    const imageIds = extractImageIds(props.note.content)
    for (const imageId of imageIds) {
      await loadImagePreview(imageId)
    }
  }

  // 添加全局粘贴事件监听器作为备用方案
  globalPasteHandler = (event: ClipboardEvent) => {
    console.log('全局粘贴事件触发')
    // 检查当前焦点是否在编辑器内
    const activeElement = document.activeElement
    const editorElement = document.querySelector('.content-editor')

    if (activeElement === editorElement) {
      console.log('焦点在编辑器内，处理全局粘贴事件')
      handlePaste(event)
    } else {
      console.log('焦点不在编辑器内，忽略全局粘贴事件')
    }
  }

  document.addEventListener('paste', globalPasteHandler)
  console.log('已添加全局粘贴事件监听器')
})

// 组件卸载时清理缓存和保存内容
onUnmounted(() => {
  console.log('NoteEditor组件即将卸载')
  
  // 强制保存当前内容
  forceSave()
  
  // 清理定时器
  if (autoSaveTimer) {
    clearTimeout(autoSaveTimer)
    autoSaveTimer = null
  }
  
  // 清理图片缓存
  cleanupImageCache()

  // 移除全局粘贴事件监听器
  if (globalPasteHandler) {
    document.removeEventListener('paste', globalPasteHandler)
    console.log('已移除全局粘贴事件监听器')
  }
})

/**
 * 插入Markdown格式
 * @param format 格式类型
 */
const insertFormat = (format: string): void => {
  const textarea = document.querySelector('.content-editor') as HTMLTextAreaElement
  if (!textarea) return

  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const selectedText = content.value.substring(start, end)

  let insertText = ''

  switch (format) {
    case 'bold':
      insertText = `**${selectedText || '粗体文本'}**`
      break
    case 'italic':
      insertText = `*${selectedText || '斜体文本'}*`
      break
    case 'code':
      insertText = `\`${selectedText || '代码'}\``
      break
    case 'h1':
      insertText = `# ${selectedText || '一级标题'}`
      break
    case 'h2':
      insertText = `## ${selectedText || '二级标题'}`
      break
    case 'h3':
      insertText = `### ${selectedText || '三级标题'}`
      break
    case 'list':
      insertText = `- ${selectedText || '列表项'}`
      break
    case 'link':
      insertText = `[${selectedText || '链接文本'}](url)`
      break
  }

  content.value = content.value.substring(0, start) + insertText + content.value.substring(end)
  updateContent()

  // 重新聚焦并设置光标位置
  setTimeout(() => {
    textarea.focus()
    textarea.setSelectionRange(start + insertText.length, start + insertText.length)
  }, 0)
}
</script>

<template>
  <div class="note-editor">
    <div v-if="!note" class="empty-state">
      <div class="empty-icon">
        <svg viewBox="0 0 24 24" width="48" height="48">
          <path
            fill="currentColor"
            d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"
          />
        </svg>
      </div>
      <h3>选择一个笔记开始编辑</h3>
      <p>从左侧列表中选择笔记，或创建一个新笔记</p>
    </div>

    <div v-else class="editor-container">
      <!-- 工具栏 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <button
            class="toolbar-btn"
            :class="{ active: !isPreviewMode }"
            @click="isPreviewMode = false"
            title="编辑模式"
          >
            <svg viewBox="0 0 24 24" width="16" height="16">
              <path
                fill="currentColor"
                d="M20.71,7.04C21.1,6.65 21.1,6 20.71,5.63L18.37,3.29C18,2.9 17.35,2.9 16.96,3.29L15.12,5.12L18.87,8.87M3,17.25V21H6.75L17.81,9.93L14.06,6.18L3,17.25Z"
              />
            </svg>
            编辑
          </button>
          <button
            class="toolbar-btn"
            :class="{ active: isPreviewMode }"
            @click="togglePreview"
            title="预览模式"
          >
            <svg viewBox="0 0 24 24" width="16" height="16">
              <path
                fill="currentColor"
                d="M12,9A3,3 0 0,0 9,12A3,3 0 0,0 12,15A3,3 0 0,0 15,12A3,3 0 0,0 12,9M12,17A5,5 0 0,1 7,12A5,5 0 0,1 12,7A5,5 0 0,1 17,12A5,5 0 0,1 12,17M12,4.5C7,4.5 2.73,7.61 1,12C2.73,16.39 7,19.5 12,19.5C17,19.5 21.27,16.39 23,12C21.27,7.61 17,4.5 12,4.5Z"
              />
            </svg>
            预览
          </button>
        </div>

        <div v-if="!isPreviewMode" class="toolbar-center">
          <button class="format-btn" @click="insertFormat('bold')" title="粗体">
            <svg viewBox="0 0 24 24" width="16" height="16">
              <path
                fill="currentColor"
                d="M13.5,15.5H10V12.5H13.5A1.5,1.5 0 0,1 15,14A1.5,1.5 0 0,1 13.5,15.5M10,6.5H13A1.5,1.5 0 0,1 14.5,8A1.5,1.5 0 0,1 13,9.5H10M15.6,10.79C16.57,10.11 17.25,9.02 17.25,8C17.25,5.74 15.5,4 13.25,4H7V18H14.04C16.14,18 17.75,16.3 17.75,14.21C17.75,12.69 16.89,11.39 15.6,10.79Z"
              />
            </svg>
          </button>
          <button class="format-btn" @click="insertFormat('italic')" title="斜体">
            <svg viewBox="0 0 24 24" width="16" height="16">
              <path
                fill="currentColor"
                d="M10,4V7H12.21L8.79,15H6V18H14V15H11.79L15.21,7H18V4H10Z"
              />
            </svg>
          </button>
          <button class="format-btn" @click="insertFormat('code')" title="代码">
            <svg viewBox="0 0 24 24" width="16" height="16">
              <path
                fill="currentColor"
                d="M8,3A2,2 0 0,0 6,5V9A2,2 0 0,1 4,11H3V13H4A2,2 0 0,1 6,15V19A2,2 0 0,0 8,21H10V19H8V14A2,2 0 0,0 6,12A2,2 0 0,0 8,10V5H10V3M16,3A2,2 0 0,1 18,5V9A2,2 0 0,0 20,11H21V13H20A2,2 0 0,0 18,15V19A2,2 0 0,1 16,21H14V19H16V14A2,2 0 0,1 18,12A2,2 0 0,1 16,10V5H14V3"
              />
            </svg>
          </button>
          <div class="toolbar-divider"></div>
          <button class="format-btn" @click="insertFormat('h1')" title="一级标题">H1</button>
          <button class="format-btn" @click="insertFormat('h2')" title="二级标题">H2</button>
          <button class="format-btn" @click="insertFormat('h3')" title="三级标题">H3</button>
          <div class="toolbar-divider"></div>
          <button class="format-btn" @click="insertFormat('list')" title="列表">
            <svg viewBox="0 0 24 24" width="16" height="16">
              <path
                fill="currentColor"
                d="M7,5H21V7H7V5M7,13V11H21V13H7M4,4.5A1.5,1.5 0 0,1 5.5,6A1.5,1.5 0 0,1 4,7.5A1.5,1.5 0 0,1 2.5,6A1.5,1.5 0 0,1 4,4.5M4,10.5A1.5,1.5 0 0,1 5.5,12A1.5,1.5 0 0,1 4,13.5A1.5,1.5 0 0,1 2.5,12A1.5,1.5 0 0,1 4,10.5M7,19V17H21V19H7M4,16.5A1.5,1.5 0 0,1 5.5,18A1.5,1.5 0 0,1 4,19.5A1.5,1.5 0 0,1 2.5,18A1.5,1.5 0 0,1 4,16.5Z"
              />
            </svg>
          </button>
          <button class="format-btn" @click="insertFormat('link')" title="链接">
            <svg viewBox="0 0 24 24" width="16" height="16">
              <path
                fill="currentColor"
                d="M3.9,12C3.9,10.29 5.29,8.9 7,8.9H11V7H7A5,5 0 0,0 2,12A5,5 0 0,0 7,17H11V15.1H7C5.29,15.1 3.9,13.71 3.9,12M8,13H16V11H8V13M17,7H13V8.9H17C18.71,8.9 20.1,10.29 20.1,12C20.1,13.71 18.71,15.1 17,15.1H13V17H17A5,5 0 0,0 22,12A5,5 0 0,0 17,7Z"
              />
            </svg>
          </button>
        </div>

        <div class="toolbar-right">
          <div class="save-status">
            <div class="save-indicator" :class="saveStatus">
              <svg v-if="saveStatus === 'saving'" class="save-icon spinning" viewBox="0 0 24 24" width="14" height="14">
                <path fill="currentColor" d="M12,4V2A10,10 0 0,0 2,12H4A8,8 0 0,1 12,4Z" />
              </svg>
              <svg v-else-if="saveStatus === 'saved'" class="save-icon" viewBox="0 0 24 24" width="14" height="14">
                <path fill="currentColor" d="M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z" />
              </svg>
              <svg v-else class="save-icon" viewBox="0 0 24 24" width="14" height="14">
                <path fill="currentColor" d="M17,3H5C3.89,3 3,3.9 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V7L17,3M19,19H5V5H16.17L19,7.83V19M12,12C10.34,12 9,13.34 9,15C9,16.66 10.34,18 12,18C13.66,18 15,16.66 15,15C15,13.34 13.66,12 12,12Z" />
              </svg>
              <span class="save-text">
                <template v-if="saveStatus === 'saving'">保存中...</template>
                <template v-else-if="saveStatus === 'saved' && lastSaveTime">
                  已保存 {{ lastSaveTime }}
                </template>
                <template v-else-if="saveStatus === 'saved'">已保存</template>
                <template v-else>未保存</template>
              </span>
            </div>
          </div>
          <span class="word-count">{{ wordCount }} 字</span>
        </div>
      </div>

      <!-- 标题编辑 -->
      <div class="title-section">
        <input
          v-model="title"
          @input="updateTitle"
          class="title-input"
          placeholder="输入笔记标题..."
        />
      </div>

      <!-- 内容编辑区 -->
      <div class="content-section">
        <!-- 上传进度条 -->
        <div v-if="isUploading" class="upload-progress">
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: uploadProgress + '%' }"></div>
          </div>
          <span class="progress-text">上传图片中... {{ Math.round(uploadProgress) }}%</span>
        </div>

        <textarea
          v-if="!isPreviewMode"
          v-model="content"
          @input="updateContent"
          @paste="handlePaste"
          @drop="handleDrop"
          @dragover="handleDragOver"
          @focus="() => console.log('编辑器获得焦点')"
          @blur="() => console.log('编辑器失去焦点')"
          @keydown="(e) => console.log('按键按下:', e.key, e.ctrlKey, e.code)"
          @keyup="
            (e) => {
              if (e.ctrlKey && e.key === 'v') console.log('检测到Ctrl+V组合键')
            }
          "
          class="content-editor"
          placeholder="开始写作...\n\n💡 提示：\n- 支持直接粘贴图片 (Ctrl+V)\n- 支持拖拽图片到编辑器\n- 支持Markdown语法"
        ></textarea>

        <div v-else class="content-preview" v-html="renderMarkdown(content)"></div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.note-editor {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: white;
}

.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #6c757d;
  text-align: center;
}

.empty-icon {
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-state h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
}

.editor-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 16px;
  border-bottom: 1px solid #e9ecef;
  background: #f8f9fa;
  height: 64px;
}

.toolbar-left,
.toolbar-center {
  display: flex;
  align-items: center;
  gap: 8px;
}

.toolbar-btn {
  padding: 8px 12px;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  transition: all 0.2s;
  height: 36px;
  box-sizing: border-box;
}

.toolbar-btn:hover {
  background: #e9ecef;
}

.toolbar-btn.active {
  background: #007bff;
  border-color: #007bff;
  color: white;
}

.format-btn {
  padding: 8px;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 13px;
  font-weight: 600;
  transition: all 0.2s;
  height: 36px;
  box-sizing: border-box;
  min-width: 36px;
}

.format-btn:hover {
  background: #e9ecef;
}

.toolbar-divider {
  width: 1px;
  height: 20px;
  background: #dee2e6;
  margin: 0 4px;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.save-status {
  display: flex;
  align-items: center;
}

.save-indicator {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.2s;
}

.save-indicator.saved {
  color: #28a745;
  background: rgba(40, 167, 69, 0.1);
}

.save-indicator.saving {
  color: #ffc107;
  background: rgba(255, 193, 7, 0.1);
}

.save-indicator.unsaved {
  color: #dc3545;
  background: rgba(220, 53, 69, 0.1);
}

.save-icon {
  flex-shrink: 0;
}

.save-icon.spinning {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.save-text {
  white-space: nowrap;
}

.word-count {
  font-size: 12px;
  color: #6c757d;
}

.title-section {
  padding: 16px;
  border-bottom: 1px solid #e9ecef;
}

.title-input {
  width: 100%;
  border: none;
  outline: none;
  font-size: 24px;
  font-weight: 600;
  color: #212529;
  background: transparent;
}

.title-input::placeholder {
  color: #adb5bd;
}

.content-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.content-editor {
  flex: 1;
  border: none;
  outline: none;
  padding: 16px;
  font-size: 14px;
  line-height: 1.6;
  color: #212529;
  background: transparent;
  resize: none;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
}

.content-editor::placeholder {
  color: #adb5bd;
}

.content-preview {
  flex: 1;
  padding: 16px;
  font-size: 14px;
  line-height: 1.6;
  color: #212529;
  overflow-y: auto;
  max-height: calc(100vh - 200px);
  min-height: 300px;
}

.content-preview :deep(h1) {
  font-size: 24px;
  font-weight: 600;
  margin: 24px 0 16px 0;
  color: #212529;
}

.content-preview :deep(h2) {
  font-size: 20px;
  font-weight: 600;
  margin: 20px 0 12px 0;
  color: #212529;
}

.content-preview :deep(h3) {
  font-size: 16px;
  font-weight: 600;
  margin: 16px 0 8px 0;
  color: #212529;
}

.content-preview :deep(strong) {
  font-weight: 600;
}

.content-preview :deep(em) {
  font-style: italic;
}

.content-preview :deep(code) {
  background: #f8f9fa;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
}

.content-preview :deep(pre) {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 12px 0;
}

.content-preview :deep(pre code) {
  background: none;
  padding: 0;
}

.content-preview :deep(a) {
  color: #007bff;
  text-decoration: none;
}

.content-preview :deep(a:hover) {
  text-decoration: underline;
}

/* 图片相关样式 */
.upload-progress {
  padding: 12px 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  align-items: center;
  gap: 12px;
}

.progress-bar {
  flex: 1;
  height: 6px;
  background: #e9ecef;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #007bff, #0056b3);
  border-radius: 3px;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 12px;
  color: #6c757d;
  white-space: nowrap;
}

.content-preview :deep(.markdown-image) {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin: 12px 0;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.content-preview :deep(.markdown-image:hover) {
  transform: scale(1.02);
}

.content-preview :deep(.image-loading) {
  display: inline-block;
  padding: 8px 12px;
  background: #f8f9fa;
  border: 1px dashed #dee2e6;
  border-radius: 6px;
  color: #6c757d;
  font-size: 14px;
  margin: 8px 0;
}

.content-editor {
  min-height: 300px;
  border: 2px dashed transparent;
  transition: border-color 0.2s ease;
}

.content-editor:focus {
  outline: none;
  border-color: transparent;
}

.content-editor.drag-over {
  border-color: #28a745;
  background-color: rgba(40, 167, 69, 0.05);
}
</style>
